package OnlineExam;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import java.util.*;
import OnlineExam.*;
import OnlineExam.db.*;

public final class Category extends HibernateCategory
{

	/** 
	 * Input validation.
	 */
	
		
	public ActionErrors validate(ActionMapping mapping,HttpServletRequest request) 
	{

		servlet.log ("Category Name : "+ getCategoryName());
    	servlet.log("Category Id:" + getCategoryId());      
    	servlet.log("CategoryAdmin : " + getCategoryAdmin());      

		ActionErrors errors = new ActionErrors();
    
		if (getCategoryName() == null || getCategoryName().equals("")) 
		{
      		errors.add("Category Name", new ActionMessage("error.newCategoryName"));
    	}

	
		else if (getCategoryId() == null || getCategoryId().equals("")) 
		{
      		errors.add("New CategoryId", new ActionMessage("error.newCategoryId"));
    	}

		else if (isCategoryPresent(getCategoryId()))
		{
			errors.add("CategoryId Present", new ActionMessage("error.categoryNotUnique"));
		}
	
  		else if (getCategoryAdmin() == null || getCategoryAdmin().equals("")) 
		{
      		errors.add("Category Admin", new ActionMessage("error.newCategoryAdmin"));
    	}
		
		else if (!(isEmailIdPresent (getCategoryAdmin())))
		{  
			errors.add ("No such user exists", new ActionMessage ("error.noSuchUser"));
		}
		System.out.println ("error set:" + errors);
    	return errors;	
  	}
	
	
	/**
	 *  Checks if the username is already present in the database.
	 */


	private static boolean isEmailIdPresent (String emailIdFromUser)
    {
		Session session = null;
		try
		{
			SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
       		session = sessionFactory.openSession();
		
			Query query = session.createQuery("from User in class registration.User where EmailId = :emailId and status='confirmed'");  
			query.setString("emailId", emailIdFromUser);

			List list = query.list();
			
			return (list.size() > 0);
		}
		catch (Exception e)
		{
			System.out.println("Exception.." + e);
			return false;
		}
		finally
		{
			try { if (session != null) session.flush(); session.close();}
			catch (Exception e) { System.out.println ("Exception.." + e);}
		}
	}

	private static boolean isCategoryPresent (String categoryId)
    {
		try
		{
			List list = DBUtil.select ("Category", "OnlineExam.Category", "CategoryId", categoryId);
			
			return (list.size() > 0);
		}
		catch (DBException e)
		{
			System.out.println("Exception.." + e);
			return false;
		}
	}


	/**
	 *  returns the Category Object for the given categoryId.
	 */

	public static Category retrieveCategory (String categoryId)
  	{

		try
		{
			List list = DBUtil.select ("Category", "OnlineExam.Category", "CategoryId", categoryId);
			
			return (Category) list.listIterator().next(); 
		}
		catch (DBException e)
		{
			System.out.println ("Exception..." + e);
			return null;
		}
  	}

	
	/**
	 *  retrieveQuestionsUnderCategory : Returns a list of Question objects belonging to a given category.
	 */
	
	public List retrieveQuestions() 
  	{
			
		try
		{
			return DBUtil.select ("QuestionBank", "OnlineExam.question.Question", "CategoryId", getCategoryId());
		}
		catch (DBException e)
		{
			System.out.println ("Exception..." + e);
			return null;
		}
	}


	/**
	 *  returns the list of Tests taken under a category.
	 */

   	public List retrieveTestsTaken()
   	{
		
		try
		{
			return DBUtil.select("Tests", "OnlineExam.Test", "CategoryId", getCategoryId());
		}
		catch (DBException e)
		{
			System.out.println ("Exception..." + e);
			return null;
		}    
	}

	/**
	 *  Returns a list of all the categories .
	 */

	public static List<Category> selectAllCategories ()
	{
		try 
		{
			return DBUtil.select ("Category", "OnlineExam.Category");
		}
		catch (DBException e)
		{
			System.out.println ("Exception " + e);
			return null;
		}
	}
}
